package weatherwidget.isrefluxer.bird.com.birdweatherwidget;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

import weatherwidget.isrefluxer.bird.com.birdweatherwidget.constant.WeatherConstant;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.data.DatabaseHelper;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.data.WeatherInfo;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.service.UpdateService;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.ConnectUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.DateUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.LogUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.ResourceUtil;

/**
 * Implementation of App Widget functionality.
 */
public class WeatherWidget extends AppWidgetProvider {

    private static final String TAG = "zbWeatherWidget";
    private static WeatherWidget sInstance;

    public static synchronized WeatherWidget getInstance() {
        if (sInstance == null) {
            sInstance = new WeatherWidget();
        }
        return sInstance;
    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        LogUtil.log(TAG,"updateAppWidget");
        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget);
       //   views.setTextViewText(R.id.appwidget_text, widgetText);
        updateViews(context, views);
        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    public static void updateViews(Context context, RemoteViews views) {
        views.setViewVisibility(R.id.bd_init_bg, View.INVISIBLE);
        views.setViewVisibility(R.id.bd_root_content,View.VISIBLE);
        updateTimeViews(views);
        updateWeatherViews(context,views);

    }

    private static void updateWeatherViews(Context context, RemoteViews views) {

        String locaCity = DatabaseHelper.getLocalCity(context);
        LogUtil.log(TAG,"updateWeatherViews(localCity): "+locaCity);
        WeatherInfo weatherInfo = DatabaseHelper.getTodayData(context,locaCity);
        LogUtil.log(TAG,"updateWeatherViews(weatherInfo!=null): "+(weatherInfo!=null));
        if(weatherInfo!=null){
            String weather;
            LogUtil.log(TAG,"updateWeatherViews(DateUtil.isNight()): "+(DateUtil.isNight()));
            if(DateUtil.isNight()){

                weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_NIGHT);
                if (TextUtils.isEmpty(weather)) {
                    weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_DAY);
                }

            }else{
                weather = weatherInfo.getValueByKey(WeatherInfo.WEATHER_DAY);
            }
            LogUtil.log(TAG,"updateWeatherViews(weather): "+(weather));
            String mintemper = weatherInfo.getValueByKey(WeatherInfo.MINTEMPER);
            String maxtemper = weatherInfo.getValueByKey(WeatherInfo.MAXTEMPER);
            String temper = mintemper + "\b~\b" + maxtemper
                    + context.getResources().getString(R.string.temperature_sign);
            views.setTextViewText(R.id.bd_widget_temper, weatherInfo.getValueByKey(WeatherInfo.NOWTEMPER)+context.getResources().getString(R.string.temperature_sign));

            views.setImageViewResource(R.id.bd_weather,
                    ResourceUtil.getResourceByWeather(weather, true, true));
            if (!TextUtils.isEmpty(weather) && weather.length() > 5) {
                weather = weather.substring(0, 4) + "..";
            }
            views.setTextViewText(R.id.bd_widget_weather, weather);
            String city = weatherInfo.getValueByKey(WeatherInfo.CITY_NAME);
            views.setTextViewText(R.id.bd_location_city,
                    city.substring(city.indexOf("|") + 1, city.length()));
            views.setViewVisibility(R.id.bd_weather_con, View.VISIBLE);
            views.setViewVisibility(R.id.rl_fresh_weather, View.INVISIBLE);


        }

    }

    private static void updateTimeViews(RemoteViews views) {

       String date = DateUtil.getMM_DD(System.currentTimeMillis());
        String week = DateUtil.getWeek();
        String lunar = DateUtil.getLunarDate();
        LogUtil.log("test",
                "date=" + date);
        views.setTextViewText(R.id.bd_date,date);
        views.setTextViewText(R.id.bd_week,week);
        views.setTextViewText(R.id.bd_lunar_date,lunar);

    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }

    @Override
    public void onEnabled(Context context) {
        context.startService(new Intent(context, UpdateService.class));
        super.onEnabled(context);
    }

    @Override
    public void onDisabled(Context context) {
        super.onDisabled(context);
//        context.stopService(new Intent(WeatherConstant.ACTION_START_WEATHER_SERVICE));

    }

    public void locationSuccess(final Context context, String city) {

        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);
        updateViews(context, views);
        views.setTextViewText(R.id.bd_location_city,
                city.substring(city.indexOf("|") + 1, city.length()));
        ComponentName provider = new ComponentName(context, WeatherWidget.class);
        AppWidgetManager.getInstance(context).updateAppWidget(provider,
                views);
    }

    public void locationFailure(Context context, boolean booleanExtra) {
        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);
        updateViews(context, views);
        ComponentName provider = new ComponentName(context, WeatherWidget.class);
        AppWidgetManager.getInstance(context).updateAppWidget(provider,
                views);

        if (booleanExtra) {
//            Intent i = new Intent();
//            i.setClassName("weatherwidget.isrefluxer.bird.com.birdweatherwidget",
//                    "weatherwidget.isrefluxer.bird.com.birdweatherwidget.activity.WidgetDialogActivity");
//            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            context.startActivity(i);

        } else {
//            String localCity = DatabaseHelper.getLocalCity(context);
//            if (TextUtils.isEmpty(localCity)) {
//                Intent i = new Intent();
//                i.setClassName("weatherwidget.isrefluxer.bird.com.birdweatherwidget",
//                        "weatherwidget.isrefluxer.bird.com.birdweatherwidget.activity.WidgetDialogActivity");
//                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                context.startActivity(i);
//            }
        }

    }

    public void freshClick(final Context context) {
        String last_update = DatabaseHelper.getUpdateTime(context);
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = dateFormat.parse(last_update);
            long time = date.getTime();
            if (System.currentTimeMillis() - time > WeatherConstant.UPDATE_FREQUENCY_TIME) {// 天气信息过期
                clickOperation(context);
            } else {
                RemoteViews views = new RemoteViews(context.getPackageName(),
                        R.layout.weather_widget);
                updateViews(context, views);
                ComponentName provider = new ComponentName(context, WeatherWidget.class);
                AppWidgetManager.getInstance(context).updateAppWidget(provider, views);
            }
        } catch (Exception e) {
            clickOperation(context);
        }
    }
    private void clickOperation(final Context context) {
        if (ConnectUtil.isNetworkConnected(context)) {
            context.startService(new Intent(context, UpdateService.class));
            context.sendBroadcast(new Intent(
                    WeatherConstant.ACTION_WEATHER_UPDATE));
            freshAnim(context);

        } else {
            Toast.makeText(context,
                    context.getResources().getString(R.string.no_network),
                    Toast.LENGTH_SHORT).show();
        }
    }
    private void freshAnim(final Context context) {// 刷新的帧动画
        final RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);
        views.setViewVisibility(R.id.pb_fresh_weather, View.VISIBLE);
        views.setImageViewResource(R.id.bd_fresh_weather, R.drawable.weather_widget_icon_yin_l);
        ComponentName provider = new ComponentName(context, WeatherWidget.class);
        AppWidgetManager.getInstance(context).updateAppWidget(provider,
                views);
    }

}

